package com.zju.cst.cloudApp.server.handler;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import com.zju.cst.cloudApp.command.ActionHandler;
import com.zju.cst.cloudApp.entity.Message;
import com.zju.cst.cloudApp.server.AppServer;
import com.zju.cst.cloudApp.util.XmlUtil;

public class DispacterHandler extends SimpleChannelHandler {

	private ActionMap actionMap;
	
	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		AppServer.allChannels.add(e.getChannel());
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		String msgStr = (String)e.getMessage();
		Message message = (Message)XmlUtil.xml2Obj(msgStr);
		String type = message.getType();
		ActionHandler command = actionMap.getCommand(type);
		command.execute(message);
		ctx.getChannel().close();
	}

	public ActionMap getActionMap() {
		return actionMap;
	}

	public void setActionMap(ActionMap actionMap) {
		this.actionMap = actionMap;
	}

}
